package com.run.motion.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;

import com.run.motion.config.IpConfig;
import com.run.motion.config.RuoYiConfig;
import com.run.motion.entity.Comment;
import com.run.motion.entity.Dynamic;
import com.run.motion.entity.Images;
import com.run.motion.service.ICommentService;
import com.run.motion.service.IDynamicService;
import com.run.motion.service.IImagesService;
import com.run.motion.util.FileUploadUtils;
import com.run.motion.util.page.AjaxResult;
import com.run.motion.util.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * 发布动态Controller
 * 
 * @author lyq
 * @date 2022-03-26
 */
@Api(tags = "发布动态")
@RestController
@RequestMapping("/dynamic")
public class DynamicController extends BaseController
{
    @Autowired
    private IDynamicService dynamicService;

    @Autowired
    private IImagesService imagesService;

    @Autowired
    ICommentService iCommentService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    IpConfig ipConfig;

    public final static String REDIS_FABULOU_KEY="motion:dynamic:fabulou";

    /**
     * 查询发布动态列表
     */
    @ApiOperation(value = "查询发布动态列表")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(value = "userId",required=false) String userId,
                              Dynamic dynamic)
    {
        startPage();
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<Dynamic> list = dynamicService.selectDynamicList(dynamic); // 取到动态主体
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setAvatar(ipConfig.getIp()+list.get(i).getAvatar()); // 给头像拼接地址

            List<Images> images = imagesService.selectImagesByMId(list.get(i).getMid());
            List<Comment> comments = iCommentService.selectCommentByMidList(list.get(i).getMid());
            Map<String,Object> dynamicMap = new Hashtable<>();

            for (int j = 0; j < images.size(); j++) { // 给图片拼接地址
                images.get(j).setUrl(ipConfig.getIp() +images.get(j).getUrl());
            }
//            判断是否点赞
            String key= DynamicController.REDIS_FABULOU_KEY+list.get(i).getMid();
            if (userId != null){
                Double score = redisTemplate.opsForZSet().score(key, userId + "");
                if (score!=null){
                    list.get(i).setLike(true);
                }
            }

            dynamicMap.put("dynamic",list.get(i));
            dynamicMap.put("images",images);
            dynamicMap.put("comments",comments);
            mapList.add(dynamicMap);
        }
        return getDataTable(mapList,dynamicService.getTotal());
    }

    /**
     * 根据userId获取发布动态详细信息
     */
    @ApiOperation(value = "根据userId获取发布动态详细信息")
    @GetMapping(value = "/list/userId")
    public TableDataInfo getInfoList(@RequestParam("userId") String userId)
    {
        startPage();
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<Dynamic> list = dynamicService.selectDynamicByUserIdList(userId); // 取到动态主体
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setAvatar(ipConfig.getIp()+list.get(i).getAvatar()); // 给头像拼接地址

            List<Images> images = imagesService.selectImagesByMId(list.get(i).getMid());
            List<Comment> comments = iCommentService.selectCommentByMidList(list.get(i).getMid());
            Map<String,Object> dynamicMap = new Hashtable<>();

            for (int j = 0; j < images.size(); j++) { // 给图片拼接地址
                images.get(j).setUrl(ipConfig.getIp() +images.get(j).getUrl());
            }
//            判断是否点赞
            String key= DynamicController.REDIS_FABULOU_KEY+list.get(i).getMid();
            if (userId != null){
                Double score = redisTemplate.opsForZSet().score(key, userId + "");
                if (score!=null){
                    list.get(i).setLike(true);
                }
            }

            dynamicMap.put("dynamic",list.get(i));
            dynamicMap.put("images",images);
            dynamicMap.put("comments",comments);
            mapList.add(dynamicMap);
        }
        return getDataTable(mapList,dynamicService.getTotal());
    }

    /**
     * 获取发布动态详细信息
     */
//    @ApiOperation(value = "获取发布动态详细信息")
    @GetMapping(value = "/{mid}")
    public AjaxResult getInfo(@PathVariable("mid") Long mid)
    {
        return AjaxResult.success(dynamicService.selectDynamicByMid(mid));
    }
    /**
     * 新增发布动态
     */
    @ApiOperation(value = "新增发布动态")
    @PostMapping
    public AjaxResult add(@RequestBody Dynamic dynamic){
        dynamic.setCreateTime(new Date(System.currentTimeMillis())); //添加发布时间
        if (dynamicService.insertDynamic(dynamic)>0){
            Long id = dynamicService.getId();
            Map<String,Object> map = new HashMap<>();
            map.put("code",200);
            map.put("mid",id);
            return AjaxResult.success(map);
        }
        return AjaxResult.error("发布失败");
    }
    /**
     * 上传图片
     */
    @ApiOperation(value = "上传图片")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("mid") Long mid,
                             @RequestParam("file") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            // 获取图片宽高
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            // 储存图片，并获取储存地址
            String url = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            Images images = new Images(mid,url,width,height); // 把数据加入到images对象
            imagesService.insertImages(images); // 插入数据
            return AjaxResult.success("图片上传成功");
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
//    /**
//     * 新增发布动态
//     */
//    @PostMapping
//    public AjaxResult add(@RequestParam("dynamic") String object,
//                          @RequestParam("files") MultipartFile[] files) throws IOException {
////        把字符串转成json，再把json转成对象
//        JSONObject jsonObject = JSONObject.parseObject(object);
//        Dynamic dynamic = new Dynamic();
//        dynamic.setUserId(jsonObject.getLong("userId"));
//        dynamic.setText(jsonObject.getString("text"));
//        dynamic.setLocation(jsonObject.getString("location"));
//        dynamic.setCreateTime(new Date(System.currentTimeMillis()));
//
//        if(dynamicService.insertDynamic(dynamic)>0){ // 如果动态发布成功
//            Long id = dynamicService.getId();
//            for (MultipartFile file: files) { // 如果有图片，执行相应的图片上传
//                if (!file.isEmpty())
//                {
//                    // 获取图片宽高
//                    BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//                    int height = bufferedImage.getHeight();
//                    int width = bufferedImage.getWidth();
//                    // 储存图片，并获取储存地址
//                    String url = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
//                    Images images = new Images(id,url,width,height); // 把数据加入到images对象
//                    imagesService.insertImages(images); // 插入数据
//                }
//            }
//
//            return AjaxResult.success("发布成功");
//        }
//        return AjaxResult.success("发布失败");
//    }
    /**
     * 点赞
     */
    @ApiOperation(value = "点赞")
    @PutMapping
    public AjaxResult edit(@RequestBody Dynamic dynamic)
    {
        if (dynamicService.updateDynamic(dynamic)>0){
            return AjaxResult.success("点赞成功");
        }
        return AjaxResult.error("点赞失败");
    }

    @ApiOperation(value = "Redis点赞")
    @PutMapping("/dynamic/{userId}")
    public AjaxResult redisEdit(@RequestBody Dynamic dynamic,@PathVariable(value = "userId",required=false) String userId)
    {
        if (userId==null){
            return AjaxResult.error("请先登录");
        }

        String key=REDIS_FABULOU_KEY+dynamic.getMid();
//        判断集合中是否有当前用户ID
        Double score = redisTemplate.opsForZSet().score(key, userId + "");
        if (score==null){
            // 修改点赞数量
            boolean update = dynamicService.update(dynamic.getMid());

//            数据库修改成功才修改
            if (update){
                redisTemplate.opsForZSet().add(key, userId+"",System.currentTimeMillis());
                dynamic.setLike(true);
            }
        }else{
            boolean update = dynamicService.updatedecr(dynamic.getMid());
//            数据库修改成功才修改
            if (update){
                redisTemplate.opsForZSet().remove(key,userId+"");
                dynamic.setLike(false);
            }
        }
        return AjaxResult.success(dynamic);
    }

    /**
     * 删除发布动态
     */
    @ApiOperation(value = "删除发布动态")
	@DeleteMapping("/{mids}")
    public AjaxResult remove(@PathVariable Long[] mids)
    {
        return toAjax(dynamicService.deleteDynamicByMids(mids));
    }
}
